package com.juick.mod;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

/**
+ *  This activity opens on VIEW intents for URLs like http://juick.com/user/id
+ *  and starts {@link ThreadActivity} or {@link MessagesActivity} to
+ *  show thread or blog specified in the URL.
+ *  If the URL cannot be parsed, {@link MainActivity} is started.
+ *  Currently URLs to thread (http://juick.com/id or http://juick.com/user/id)
+ *  are supported. 
+ *  TODO: URLs to user's blog (http://juick.com/user) support (need to take user's ID by it's name).
+ *  @author gelin
+ */
public class UrlActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent == null) {
            startMain();
            return;
        }
        
        Uri uri = intent.getData();
        List<String> paths = uri.getPathSegments();
        if (paths.size() == 0) {
            startMain();
            return;
        }
        
        String lastPath = paths.get(paths.size() - 1);
        try {
            int messageId = Integer.parseInt(lastPath);
            startThread(messageId);
            return;
        } catch (NumberFormatException e) {
            /*  TODO
            if (paths.size() > 1) {
                String user = paths.get(paths.size() - 1);
                startUser(user);
                return;
            }
            */
        }
        //startUser(lastPath);  //TODO
        startMain();
    }
    
    void startMain() {
        finish();
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    void startThread(int messageId) {
        finish();
        Intent intent = new Intent(this, MessagesActivity.class);
        intent.putExtra("go", messageId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    
    void startUser(String user) {
        finish();
        Intent intent = new Intent(this, MessagesActivity.class);
        //intent.putExtra("uid", ???);    //TODO
        intent.putExtra("uname", user);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    

}
